<template>
  <div>
    <div class="comment-form bg">
      <el-input
        v-model="commentText"
        class="comment-input"
        type="textarea"
        :rows="5"
        placeholder="请输入内容,不得超过200字"
        maxlength="200"
        show-word-limit
      />
      <el-button type="primary" @click="saveComment">发表评论</el-button>
    </div>
    <div class="comment-list bg">
      <div
        v-for="(item, index) in commentList"
        :key="index"
        class="comment-item"
      >
        <div class="header">
          <img :src="item.header" />
        </div>
        <div class="comment-main">
          <div class="nickname">{{ item.nickname }}</div>
          <div class="time">发表于 {{ item.createdTime }}</div>
          <div class="content">{{ item.content }}</div>
        </div>
      </div>
      <el-pagination
        class="pageable-container"
        background
        :current-page="params.page"
        :page-sizes="[10, 15, 20]"
        :page-size="params.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="count"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { save, getByBlogId } from "@/api/blog-comment";

export default {
  props: {
    blogId: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      commentText: "",
      header: require("@/assets/header.gif"),
      params: {
        page: 1,
        limit: 10,
      },
      count: 0,
      commentList: [],
    };
  },
  watch: {
    blogId: {
      immediate: true,
      handler: function () {
        this.getByBlogId();
      },
    },
  },
  methods: {
    handleSizeChange(val) {
      this.params.limit = val;
      this.getByBlogId();
    },
    handleCurrentChange(val) {
      this.params.page = val;
      this.getByBlogId();
    },
    // 根据博客id查询评论
    getByBlogId() {
      this.params.blogId = this.blogId;
      getByBlogId(this.params).then((res) => {
        this.commentList = res.data;
        this.count = parseInt(res.count);
      });
    },
    // 保存评论
    saveComment() {
      save({ blogId: this.blogId, content: this.commentText }).then((res) => {
        this.getByBlogId();
        this.commentText = "";
      });
    },
  },
};
</script>

<style src="./comment.css" scoped>
</style>
